package com.budwk.app.ocr_general;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.constants.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

/**
 * Http Client 工具类
 */

@Slf4j
public class HttpUtil {

	/**
	 * post请求 json参数传递
	 *
	 * @param url 请求url
	 * @param json 请求参数
	 * @param headerMap 请求头参数
	 * @return 查询结果
	 */
	public static JSONObject doPostByJson(String url, JSONObject json, Map<String, String> headerMap) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		try {
			StringEntity s = new StringEntity(json.toString());
			s.setContentEncoding(StandardCharsets.UTF_8.toString());
			s.setContentType("application/json");
			post.setEntity(s);
			if (headerMap != null && headerMap.size() > 0) {
				Set<Map.Entry<String, String>> entries = headerMap.entrySet();
				for (Map.Entry<String, String> entry : entries) {
					post.addHeader(entry.getKey(), entry.getValue());
				}
			}
			HttpResponse res = httpClient.execute(post);
			// 解析结果集
			// 失败情况处理
			if (res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				return getFailResult(res);
			}
			HttpEntity entity = res.getEntity();
			String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
			return JSONObject.parseObject(result);
		} catch (Exception e) {
			log.error("doPostByJson error: ", e);
			throw new RuntimeException(e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
	}

	/**
	 * get请求
	 *
	 * @param url 请求url
	 * @param paramMap 请求参数
	 * @return
	 */
	public static JSONObject sendGet(String url, Map<String, String> paramMap, Map<String, String> headerMap) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String param = StringUtils.EMPTY;
		if (paramMap != null && paramMap.size() > 0) {
			StringBuilder stringBuilder = new StringBuilder();
			// 组装参数
			stringBuilder.append(url)
					.append(CommonConstants.QUESTION_MARK);
			Set<Map.Entry<String, String>> entries = paramMap.entrySet();
			for (Map.Entry<String, String> entry : entries) {
				stringBuilder.append(entry.getKey())
						.append(CommonConstants.EQUAL)
						.append(entry.getValue())
						.append(CommonConstants.ALSO);
			}
			param = stringBuilder.substring(0, stringBuilder.length() - 1);
		}
		String reqUrl = StringUtils.isEmpty(param) ? url : param;
		HttpGet httpGet = new HttpGet(reqUrl);
		if (headerMap != null && headerMap.size() > 0) {
			Set<Map.Entry<String, String>> entries = headerMap.entrySet();
			for (Map.Entry<String, String> entry : entries) {
				httpGet.addHeader(entry.getKey(), entry.getValue());
			}
		}
		try {
			HttpResponse res = httpClient.execute(httpGet);
			if (res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				return getFailResult(res);
			}
			HttpEntity entity = res.getEntity();
			String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
			return JSONObject.parseObject(result);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			httpClient.getConnectionManager().shutdown();
		}
	}

	/**
	 * 解析失败结果集
	 *
	 * @param res
	 * @return
	 * @throws IOException
	 */
	private static JSONObject getFailResult(HttpResponse res) throws IOException {
		// 获取响应输入流
		InputStream inStream = res.getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8));
		StringBuilder strber = new StringBuilder();
		String line;
		while ((line = reader.readLine()) != null)
			strber.append(line + "\n");
		reader.close();
		inStream.close();
		return JSONObject.parseObject(strber.toString());
	}
}
